package com.fxx.face.http.http;


import com.fxx.face.http.common.AuthService;
import com.fxx.face.http.utils.LoggerUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * @ProjectName: HttpRequestLibs
 * @Package: com.fxx.http.libs.http
 * @ClassName: HttpServiceManager
 * @Description:
 * @Author: 付小歆
 * @CreateDate: 2021/12/9 15:20
 */
public class HttpServiceManager {
    private static final int DEFAULT_CONNECT_TIME = 12;
    private static final int DEFAULT_WRITE_TIME = 12;
    private static final int DEFAULT_READ_TIME = 12;
    private static OkHttpClient okHttpClient;
    private static Retrofit retrofit;

    private HttpServiceManager(){
        retrofit = new Retrofit.Builder()
                .client(initOkHttp())
                .baseUrl(AuthService.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())      //添加 String类型[ Scalars (primitives, boxed, and String)] 转换器
                .addConverterFactory(GsonConverterFactory.create())         //添加 json数据类型 bean->json
                .build();
    }

    public static OkHttpClient initOkHttp(){
        if (okHttpClient == null){
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(
                    new HttpLoggingInterceptor.Logger() {
                        @Override
                        public void log(String message) {
                            LoggerUtil.d(message);
                        }
                    }
            );
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)
                    .readTimeout(DEFAULT_READ_TIME,TimeUnit.SECONDS)
                    .writeTimeout(DEFAULT_WRITE_TIME,TimeUnit.SECONDS)
                    .addInterceptor(loggingInterceptor)
                    .build();
        }
        return okHttpClient;
    }

    private static class SignletonHolder{
        private static final HttpServiceManager instance = new HttpServiceManager();
    }

    public static HttpServiceManager getInstance(){
        return SignletonHolder.instance;
    }

    public <T> T create(Class<T> service) {
        return retrofit.create(service);
    }
}
